import React from 'react';
import { Button, Input, message } from 'antd';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import { mapConfig } from 'Constants/mapConstants';
import './index.scss';

const Search = Input.Search;
const normalImage = 'images/dispatch/icon_plan_normal.png';
const lightImage = 'images/dispatch/icon_plan_light.png';
class SpecialManage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 16, //地图级别,
      searchValue: '',
      selectIcon: '',
      defaultdata: '',
    };
    this.onLoad = ::this.onLoad;
    this.initMap = ::this.initMap;
    this.initInfo = ::this.initInfo;
  }
  componentDidMount() {
    this.initMap();
    this.initInfo();
  }
  initMap() {
    //经纬度地图显示；
    this.map = new T.Map('mapContent');
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //先清除地图覆盖物，在显示
    // this.map.clearOverLays();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), 16);
  }
  initInfo() {
    const { searchValue } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/archives',
      query: {
        title_like: searchValue
      },
      success: (json) => {
        this.setState({
          defaultdata: json
        }, () => {
          if (json.length > 0) {
            const data = json.map(item => new T.LngLat(item.longitude, item.lartitude));
            const newData = this.map.getViewport(data);
            this.map.panTo(new T.LngLat(newData.center.lng, newData.center.lat), newData.zoom);
          }
          this.onLoad();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  componentWillReceiveProps() {
    this.map.checkResize();
  }
  onLoad() {
    const data = this.state.defaultdata;
    const self = this;
    const { selectIcon } = this.state;
    for (let i = 0; i < data.length; i++) {
      const icon1 = new T.Icon({
        iconUrl: selectIcon === data[i].id ? lightImage : normalImage,
        iconSize: new T.Point(60, 60),
        iconAnchor: new T.Point(30, 60)
      });
      //向地图上添加自定义标注
      const marker1 = new T.Marker(new T.LngLat(data[i].longitude, data[i].lartitude), { icon: icon1 });
      this.map.addOverLay(marker1);
      // icon click
      marker1.addEventListener('click', () => {
        self.setState({
          selectData: data[i],
          selectIcon: data[i].id
        });
        this.map.clearOverLays();
        self.onLoad(data);
        this.infoWin = new T.InfoWindow();
        const lnglat = new T.LngLat(data[i].longitude, data[i].lartitude);
        this.infoWin.setLngLat(lnglat);
        this.infoWin.setOffset([0, -50]);
        this.infoContent = `<div class="info-window-wrap">
                                <div class="content">
                                <div class="name">${data[i].title}</div>
                                <div class="content-detail">${data[i].introduction}</div>
                                <div class="detail" id=${`${data[i].id}`}>查看详情</div>
                                </div> 
                              </div>
                              `;
        this.infoWin.setContent(this.infoContent);
        this.map.addOverLay(this.infoWin);
        document.getElementById(`${data[i].id}`).onclick = (e) => {
          this.props.dispatch(routerActions.push(`/system/dispatch/support/special_manage/detail/${e.target.id}`));
          e.stopPropagation();
        };
      }, false);
    }
  }
  handleSearch(value) {
    this.setState({
      searchValue: value.trim()
    }, () => {
      this.initInfo();
    });
  }
  handleClick() {
    this.props.dispatch(routerActions.push('/system/dispatch/support/special_manage/list'));
  }
  render() {
    return (
      <div className="tlypica-plan-page">
        <div className="map-wrap" id="mapContent" >
          <div className="left-search">
            <Search
              placeholder="请输入关键词"
              style={{ width: 260 }}
              onSearch={this.handleSearch.bind(this)}
            />
          </div>
          <div className="right-btn" onClick={this.handleClick.bind(this)}>
            <Button className="btn" >
              专题档案管理
            </Button>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.mapReducer
  };
}

export default connect(mapStateToProps)(SpecialManage);
